<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px;">
      <el-input placeholder="生猪ID" style="margin-left:5px;float:left;width:100px;" />
      <el-input placeholder="饲养地" style="margin-left:5px;float:left;width:150px;" />
      <el-input placeholder="性状" style="margin-left:5px;float:left;width:150px;" />
      <el-select v-model="search_sex" placeholder="性别" style="margin-left:5px;float:left;width:120px;">
        <el-option label="公" value="1" />
        <el-option label="母" value="2" />
      </el-select>
      <el-select v-model="search_checkstatus" placeholder="检疫状态" style="margin-left:5px;float:left;width:120px;">
        <el-option label="已检疫" value="1" />
        <el-option label="未检疫" value="2" />
      </el-select>
      <el-select v-model="search_splitstatus" placeholder="分块状态" style="margin-left:5px;float:left;width:120px;">
        <el-option label="已分块" value="1" />
        <el-option label="未分块" value="2" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" style="margin-left:5px;float:left;width:100px;">搜索</el-button>
      <el-button
        type="primary"
        style="float:right"
        @click="newRow"
      >新增一只生猪</el-button>
    </el-row>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="45"
      />
      <el-table-column align="center" label="ID" width="45">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="饲养地" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.breed_place }}
        </template>
      </el-table-column>
      <el-table-column label="重量" show-overflow-tooltip align="center" width="70">
        <template slot-scope="scope">
          {{ scope.row.weight }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="50" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.sex === 1?'公':'母' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性状" width="70" align="center" prop="traits">
        <template slot-scope="scope">
          {{ scope.row.traits }}
        </template>
      </el-table-column>
      <el-table-column class-name="check_status" label="检疫状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.check_status | statusFilter">{{ scope.row.check_status === 1 ? '通过' : '未通过' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否已被分块" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.cut_state | statusFilter">{{ scope.row.cut_state === 1 ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="check_id" label="检疫许可证号" width="200">
        <template slot-scope="scope">
          {{ scope.row.check_id }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="out_date" label="出栏时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.out_date }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="280">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showsplit(scope.row)">分块</el-button>
          <el-button type="info" size="mini" @click="editRow(scope.row)">编辑</el-button>
          <el-button :loading="buttonloading" size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="rowdata" title="生猪分块" :visible.sync="splitvisable">
      <span>猪总重量：{{ rowdata.weight }} kg</span>
      <el-button type="primary" style="padding: 7px;float:right;" @click="addpart">+</el-button>
      <el-table v-loading="splitloading" :data="rowdata.cut_list" max-height="400" :summary-method="getSummaries" show-summary>
        <el-table-column label="重量" align="center" prop="weight">
          <template slot-scope="scope">
            <el-input v-model="scope.row.weight" type="number" placeholder="需要分割的重量" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.part_name" placeholder="需要分割部位的名称" />
          </template>
        </el-table-column>
        <el-table-column label=" " width="50">
          <template slot-scope="scope">
            <el-button type="danger" style="padding: 8px;float:right;" @click="subpart(scope.row)">-</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center; margin-top:20px;">
        <el-button type="danger" @click="clearcut">清空</el-button>
        <el-button type="primary" @click="submitcut">提交</el-button>
        <el-button type="info" @click="cancelcut">取消</el-button>
      </div>
    </el-dialog>
    <div class="block" style="margin:10px;">
      <span style="margin-right:5px;">选中 {{ multipleSelection.length }} 项 批量操作</span>
      <el-button :loading="buttonloading" type="danger" @click="deleteRow(multipleSelection)">删除</el-button>
      <el-button :loading="buttonloading" type="success" @click="onSetPass(multipleSelection)">置检疫</el-button>
      <el-button :loading="buttonloading" type="info" @click="onSetUnPass(multipleSelection)">置未检疫</el-button>
    </div>
    <div class="block" style="text-align:center;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pagesize"
        :page-sizes="[10, 15, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalcount"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import { listPig, deletePig, updatePassByID } from '@/api/pig'
import { cutlistPig, cutPork, deletePork } from '@/api/pork'
import { mapGetters } from 'vuex'
import moment from 'moment'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      search_sex: '',
      search_checkstatus: '',
      search_splitstatus: '',
      buttonloading: false,
      splitloading: true,
      currentPage: 1,
      pagesize: 15,
      totalcount: 0,
      splitvisable: false,
      editvisable: false,
      list: null,
      rowdata: {
        id: 0,
        breed_place: '',
        weight: 0,
        sex: 0,
        traits: '',
        check_status: 0,
        cut_status: 0,
        check_id: '',
        out_date: '',
        cut_list: []
      },
      listLoading: true,
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters([
      'enter_id'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    fetchData() {
      this.listLoading = true
      listPig({ current: this.currentPage, size: 15, enter_id: this.$store.getters.enter_id }).then(response => {
        this.list = response.obj.records
        this.list.forEach((x) => { x.out_date = moment(x.out_date).format('YYYY-MM-DD HH:mm:ss') })
        this.listLoading = false
        this.totalcount = response.obj.total
      }).catch(() => { this.listLoading = false })
    },
    editRow(row) {
      this.$router.push({ path: '/pig/addpig', query: { id: row.id, type: 'edit' }})
    },
    addpart() {
      this.rowdata.cut_list.push({ id: 0, weight: undefined, part_name: '' })
    },
    subpart(row) {
      this.$confirm('此操作将删除此条信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePork({ deletearray: [row.id] }).then(() => {
          for (let i = 0; i < this.rowdata.cut_list.length; i++) {
            console.log(row)
            if (this.rowdata.cut_list[i].weight === row.weight && this.rowdata.cut_list[i].part_name === row.part_name) {
              this.rowdata.cut_list.splice(i, 1)
              break
            }
          }
          this.$message('删除成功')
        })
      })
    },
    clearcut() {
      this.$confirm('此操作将清空分块信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePork({ deletearray: this.rowdata.cut_list.map((x) => x.id) }).then(() => {
          this.rowdata.cut_list.splice(0, this.rowdata.cut_list.length)
        })
      })
    },
    submitcut() {
      let total = 0
      for (let i = 0; i < this.rowdata.cut_list.length; i++) {
        total += Number(this.rowdata.cut_list[i].weight)
      }
      if (total > this.rowdata.weight) {
        this.$confirm('分割后的总质量大于目标总质量，是否继续提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.addcut()
        }).catch(() => {
          return
        })
      } else {
        this.addcut()
      }
    },
    addcut() {
      this.splitloading = true
      const arr = { array: [], eid: this.$store.getters.enter_id }
      for (let i = 0; i < this.rowdata.cut_list.length; i++) {
        arr.array.push({ id: this.rowdata.cut_list[i].id, enter_id: this.$store.getters.enter_id, part_name: this.rowdata.cut_list[i].part_name, weight: this.rowdata.cut_list[i].weight, cut_date: new Date(), parent: this.rowdata.id, buy: 0 })
      }
      cutPork(arr).then(() => {
        this.$message('添加成功')
        this.splitloading = false
      }).catch(() => { this.splitloading = false })
    },
    cancelcut() {
      this.splitvisable = false
    },
    showsplit(row) {
      this.splitvisable = true
      this.splitloading = true
      this.rowdata = row
      console.log(row)
      cutlistPig({ porkid: row.id, eid: this.$store.getters.enter_id }).then(response => {
        this.rowdata.cut_list = response.obj
        this.splitloading = false
      }).catch(() => { this.splitloading = false })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = data.length + ' 项'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(3)
          sums[index] += ' kg'
        } else {
          sums[index] = ' '
        }
      })
      return sums
    },
    newRow() {
      this.$router.push({ path: '/pig/addpig' })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.handleCurrentChange()
    },
    handleCurrentChange(val) {
      this.list = null
      this.listLoading = true
      listPig({ current: this.currentPage, size: this.pagesize, enter_id: this.$store.getters.enter_id }).then(response => {
        this.list = response.obj.records
        this.list.forEach((x) => { x.out_date = moment(x.out_date).format('YYYY-MM-DD HH:mm:ss') })
        this.listLoading = false
      }).catch(() => { this.listLoading = false })
    },
    deleteRow(row) {
      if (!(row instanceof Array)) {
        row = [row]
      }
      if (row.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选中一项'
        })
        return
      }
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.buttonloading = true
        deletePig(row.map(x => x.id)).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          for (let i = 0; i < this.list.length; i++) {
            for (let j = 0; j < row.length; j++) {
              if (this.list[i].id === row[j].id) {
                this.list.splice(i, 1)
                i--
                row.splice(j, 1)
                j--
                break
              }
            }
          }
          this.buttonloading = false
        })
      }).catch((reason) => {
        console.log(reason)
        this.buttonloading = false
      })
    },
    onSetPass(value) {
      if (value.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选中一项'
        })
        return
      }
      this.buttonloading = true
      const data = { arr: value.map((x) => { return x.id }), type: 1 }
      updatePassByID(data).then((response) => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        for (let i = 0; i < this.list.length; i++) {
          for (let j = 0; j < value.length; j++) {
            if (this.list[i].id === value[j].id) {
              this.list[i].check_status = 1
              break
            }
          }
        }
        this.buttonloading = false
      }).catch(() => { this.buttonloading = false })
    },
    onSetUnPass(value) {
      if (value.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选中一项'
        })
        return
      }
      this.buttonloading = true
      const data = { arr: value.map((x) => { return x.id }), type: 0 }
      updatePassByID(data).then((response) => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        for (let i = 0; i < this.list.length; i++) {
          for (let j = 0; j < value.length; j++) {
            if (this.list[i].id === value[j].id) {
              this.list[i].check_status = 0
              break
            }
          }
        }
        this.buttonloading = false
      }).catch(() => { this.buttonloading = false })
    }
  }
}
</script>
